package com.lzh.spring;

import java.beans.Introspector;
import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;

public class LzhApplicationContext {
    private Class configClass;
    private ConcurrentHashMap<String,BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();
    private ConcurrentHashMap<String,Object> singletonObjects = new ConcurrentHashMap<>();
    private ArrayList<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();

    public LzhApplicationContext(Class config){
        this.configClass = config;

        //判断类中是否存在注解ComponentScan
        if(this.configClass.isAnnotationPresent(ComponentScan.class)){
            //获取配置类中的注解值
            ComponentScan componentScanAnnotation = (ComponentScan)configClass.getAnnotation(ComponentScan.class);
            String path = componentScanAnnotation.value();//扫描路径 com.lzh.service

            //路径格式化
            path = path.replace(".","/"); //com/lzh/service
            ClassLoader classLoader = LzhApplicationContext.class.getClassLoader();
            URL resource = classLoader.getResource(path);

            //遍历路径下的文件
            File file = new File(resource.getFile());
            if(file.isDirectory()){
                File[] files = file.listFiles();
                for (File f : files) {
                    String fileName = f.getAbsolutePath();
                    if(fileName.endsWith(".class")){
                        String className = fileName.substring(fileName.indexOf("com"), fileName.indexOf(".class"));
                        className = className.replace("\\", ".");
                        try {
                            Class<?> aClass = classLoader.loadClass(className);
                            BeanDefinition beanDefinition = new BeanDefinition();
                            beanDefinition.setType(aClass);
                            if(aClass.isAnnotationPresent(Component.class)){
                                //判断这个类是否实现BeanPostProcessor
                                if (BeanPostProcessor.class.isAssignableFrom(aClass)){
                                    BeanPostProcessor instance =(BeanPostProcessor) aClass.newInstance();
                                    beanPostProcessorList.add(instance);
                                }
                                String beanName = aClass.getAnnotation(Component.class).value();
                                if(beanName.equals("")){
                                    beanName = Introspector.decapitalize(aClass.getSimpleName());
                                }

                                //bean
                                if(aClass.isAnnotationPresent(Scope.class)){
                                    Scope scpaAnnotation = aClass.getAnnotation(Scope.class);
                                    String scope = scpaAnnotation.value();
                                    beanDefinition.setCope(scope);
                                }else{
                                    beanDefinition.setCope("singleton");
                                }
                                beanDefinitionMap.put(beanName,beanDefinition);
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                }
            }

            //实例化单例bean
            for (String beanName : beanDefinitionMap.keySet()) {
                BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
                if (beanDefinition.getCope().equals("singleton")){
                    Object bean = createBean(beanName,beanDefinition);
                    singletonObjects.put(beanName,bean);
                }
            }
        }
    }

    private Object createBean(String beanname,BeanDefinition beanDefinition){
        Class aClass = beanDefinition.getType();

        Object instance = null;
        try {
            instance = aClass.getConstructor().newInstance();
            //依赖注入
            //获取类所有的属性
            for (Field f : aClass.getDeclaredFields()) {
                if (f.isAnnotationPresent(Autowire.class)){
                    f.setAccessible(true);
                    f.set(instance,getBean(f.getName()));
                }
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

        //判断对象是否实现BeanNameAware方法
        if (instance instanceof BeanNameAware){
            ((BeanNameAware) instance).setBeanName(beanname);
        }

        for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
            beanPostProcessor.postProcessBeforeInitialization(beanname,instance);
        }

        //初始化
        if (instance instanceof InitializationBean){
            ((InitializationBean) instance).afterPropertySet();
        }

        for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
            beanPostProcessor.postProcessAfterInitialization(beanname,instance);
        }
        //BeanPost初始化后 AOP
        return instance;
    }

    public Object getBean(String beanName){
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        if(beanDefinition==null){
            throw new NullPointerException();
        }else{
            String cope = beanDefinition.getCope();
            if (cope.equals("singleton")){
                //直接从单例池找
                Object bean = singletonObjects.get(beanName);
                if(bean==null){
                    Object o = createBean(beanName, beanDefinition);
                    singletonObjects.put(beanName,o);
                }
                return bean;
            }else{
                return createBean(beanName,beanDefinition);
            }
        }
    }
}
